import logging
from pathlib import Path
from typing import Optional
from rich.console import Console
from rich.logging import RichHandler

console = Console()

class ShellGPTLogger:
    def __init__(self, name: str = "shellgpt", level: int = logging.INFO):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)
        # Remove existing handlers
        for handler in self.logger.handlers[:]:
            self.logger.removeHandler(handler)
        # Add rich handler for console output
        rich_handler = RichHandler(
            console=console,
            show_time=True,
            show_path=False,
            markup=True,
            rich_tracebacks=True
        )
        rich_handler.setFormatter(
            logging.Formatter("%(message)s")
        )
        self.logger.addHandler(rich_handler)

    def debug(self, message: str) -> None:
        """Log debug message."""
        self.logger.debug(message)

    def info(self, message: str) -> None:
        """Log info message."""
        self.logger.info(message)

    def warning(self, message: str) -> None:
        """Log warning message."""
        self.logger.warning(message)

    def error(self, message: str) -> None:
        """Log error message."""
        self.logger.error(message)

    def critical(self, message: str) -> None:
        """Log critical message."""
        self.logger.critical(message)

    def exception(self, message: str) -> None:
        """Log exception with traceback."""
        self.logger.exception(message)

# Global logger instance
logger = ShellGPTLogger()

def setup_file_logging(log_file: Optional[Path] = None) -> None:
    if log_file is None:
        log_file = Path.home() / ".shellgpt" / "shellgpt.log"
    # Create log directory if it doesn't exist
    log_file.parent.mkdir(parents=True, exist_ok=True)
    # Add file handler
    file_handler = logging.FileHandler(log_file, encoding='utf-8')
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    )
    logger.logger.addHandler(file_handler)

def log_function_call(func_name: str, args: dict) -> None:
    logger.debug(f"Calling {func_name} with args: {args}")

def log_error(error: Exception, context: str = "") -> None:
    message = f"Error in {context}: {error}" if context else str(error)
    logger.error(message)
